/*
 * utils.h
 *
 *  Created on: Nov 20, 2024
 *      Author: Vinson
 */

#ifndef INC_UTILS_H_
#define INC_UTILS_H_



// utility defines
#define _2_SQRT3 			(1.15470053838f)
#define _SQRT3 				(1.73205080757f) /* sqrt(3) */
#define _1_SQRT3 			(0.57735026919f) /* sqrt(3) / 3 */
#define _SQRT3_2 			(0.86602540378f) /* sqrt(3) / 2 */
#define _SQRT2 				(1.41421356237f) /* sqrt(2)*/
#define _120_D2R 			(2.09439510239f) /* 2pi * 120 / 360 */
#define _PI 				(3.14159265359f)
#define _PI_2 				(1.57079632679f)
#define _PI_3 				(1.0471975512f)
#define _2PI 				(6.28318530718f)
#define _3PI_2 				(4.71238898038f)
#define _PI_6 				(0.52359877559f)

//#define _RPM_TO_RADS 		(0.10471975512f)  /*pi/30*/
#define _RPM_TO_RADS(rpm)	(rpm * 2 * _PI / 60)
#define _RADS_TO_RPM(rad)	(rad * 60 / (2 * _PI))

#define P_2F(x) (int)(x), abs(((x)-(int)(x))*100)  // "%d.%.2d"
#define P_3F(x) (int)(x), abs(((x)-(int)(x))*1000) // "%d.%.3d"

//#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
//#define NULL 0

#ifndef container_of
#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - offsetof(type, member)))
#endif

#if !__STRICT_ANSI__ && __GNUC__ >= 3

#ifndef sign
#define sign(a) ({                  \
        typeof(a) __a = (a);        \
        __a < 0 ? -1 : (__a > 0);   \
    })
#endif

#ifndef max
#define max(a, b) ({                \
        typeof(a) __a = (a);        \
        typeof(b) __b = (b);        \
        __a > __b ? __a : __b;      \
    })
#endif

#ifndef min
#define min(a, b) ({                \
        typeof(a) __a = (a);        \
        typeof(b) __b = (b);        \
        __a < __b ? __a : __b;      \
    })
#endif

#ifndef clip
#define clip(a, b, c) ({                            \
        typeof(a) __a = (a);                        \
        typeof(b) __b = (b);                        \
        typeof(c) __c = (c);                        \
        __a < __b ? __b : (__a > __c ? __c : __a);  \
    })
#endif

#ifndef swap
#define swap(a, b) \
    do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
#endif

#ifndef __weak
#define __weak  __attribute__((weak))
#endif

#else

// simple version without GCC's statement expression ({...})
#ifndef sign
#define sign(a) (((a) < 0) ? -1 : ((a) > 0))
#endif

#ifndef max
#define max(a, b) ((a) > (b) ? (a) : (b))
#endif

#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif

#ifndef clip
#define clip(a, b, c) ((a) < (b) ? (b) : ((a) > (c) ? (c) : (a)))
#endif

#endif

#endif /* INC_UTILS_H_ */
